﻿// <copyright file="CreditCheck.cs" company="Microsoft">
// Copyright (c) 2012 All Rights Reserved
// </copyright>
// <author>Microsoft</author>
// <date>2/4/2012 4:23:51 PM</date>
// <summary>Implements the CreditCheck Workflow Activity.</summary>
namespace XRM.Solutions.FrameworkSample.Workflow
{
    using System;
    using System.Activities;
    using System.ServiceModel;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Workflow;
    using Microsoft.Xrm.Sdk.Query;
    using XRM.Framework.Core;
    using XRM.Solutions.FrameworkSample.Common.Entities;
    using XRM.Solutions.FrameworkSample.Common;

    public sealed class CreditCheck : CodeActivity
    {
        #region Input Parameters

        [Input("Credit Check Type")]
        [RequiredArgument()]
        public InArgument<string> CreditCheckType { get; set; }

        #endregion

        #region Output Parameters

        [Output("Score")]
        public OutArgument<int> Score { get; set; }

        #endregion

        /// <summary>
        /// Executes the workflow activity.
        /// </summary>
        /// <param name="executionContext">The execution context.</param>
        protected override void Execute(CodeActivityContext executionContext)
        {
            // Create the tracing service
            ITracingService tracingService = executionContext.GetExtension<ITracingService>();

            if (tracingService == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve tracing service.");
            }

            tracingService.Trace("Entered CreditCheck.Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}",
                executionContext.ActivityInstanceId,
                executionContext.WorkflowInstanceId);

            // Create the context
            IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();

            if (context == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve workflow context.");
            }

            tracingService.Trace("CreditCheck.Execute(), Correlation Id: {0}, Initiating User: {1}",
                context.CorrelationId,
                context.InitiatingUserId);

            IOrganizationServiceFactory serviceFactory =
                executionContext.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService service =
                serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                Entity entity = service.Retrieve("contact", context.PrimaryEntityId,
                    new ColumnSet("firstname", "lastname", "birthdate"));

                Contact contact = entity.ToEntity<Contact>();

                ICreditCheckService creditCheckService =
                    XrmContainer.Instance.Resolve<ICreditCheckService>();

                int result =
                    creditCheckService.RunCreditCheck(CreditCheckType.Get(executionContext),
                                                    contact.FirstName, contact.LastName,
                                                    contact.BirthDate.Value);

                Score.Set(executionContext, result);
            }
            catch (FaultException<OrganizationServiceFault> e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());

                // Handle the exception.
                throw;
            }

            tracingService.Trace("Exiting CreditCheck.Execute(), Correlation Id: {0}", context.CorrelationId);
        }
    }
}